<?php

namespace frontend\controllers;

use Yii;
use frontend\models\ShopOrder;
use frontend\models\ShopOrderSearcher;
//use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use frontend\models\Address;
use yii\helpers\Url;
use frontend\models\OrderDetail;
use frontend\models\Cart;
use \frontend\models\Product;
use yii\data\ActiveDataProvider;

/**
 * ShopOrderController implements the CRUD actions for ShopOrder model.
 */
//class ShopOrderController extends Controller
class ShopOrderController extends SuperController {

	/**
	 * @inheritdoc
	 */
	public $userId;

	public function behaviors() {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['POST'],
				],
			],
		];
	}

	/**
	 * Lists all ShopOrder models.
	 * @return mixed
	 */
	public function actionIndex() {
		if ($this->isGust()) {
			return $this->redirect(Url::toRoute('site/login'));
		}
		$searchModel = new ShopOrderSearcher();
//		$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
		$query = ShopOrder::find()->where("userId=" . \Yii::$app->user->id);

		// add conditions that should always apply here

		$dataProvider = new ActiveDataProvider([
			'query' => $query,
		]);
		return $this->render('index', [
					'searchModel' => $searchModel,
					'dataProvider' => $dataProvider,
		]);
	}

	/**
	 * Displays a single ShopOrder model.
	 * @param string $id
	 * @return mixed
	 */
	public function actionView($id) {
		$model = $this->findModel($id);
		if ($model->userId != $this->userId) {
			return $this->error("你没有权限访问该页面");
		}
		$addressModel = Address::find()->where("addressId=$model->addressId")->one();
		$orderDetailList = OrderDetail::find()->where("orderId=$model->orderId")->all();
		$productList;
		foreach ($orderDetailList as $orderDetailUnit) {
			$productList[$orderDetailUnit->detailId] = Product::find()->where("productId=$orderDetailUnit->productId")->one();
		}
		return $this->render('view', [
					'model' => $model,
					'addressModel' => $addressModel,
					'orderDetailList' => $orderDetailList,
					'productList' => $productList,]);
	}

	/**
	 * Creates a new ShopOrder model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 * @return mixed
	 */
	public function actionCreate($type = 0) {
		$this->layout = 'layout2';
		$model = new ShopOrder();
		$post = Yii::$app->request->post();
		$userId = Yii::$app->user->id;
		$addressList = Address::findAll(["userId" => $userId]);
		$addressList = \yii\helpers\ArrayHelper::toArray($addressList);
		//处理从购物车传来的数据
		if (isset($post['cartIdC'])) {
			$cartIdList = $post['cartIdC'];
			$_SESSION['cartIdList'] = $cartIdList;
			return $this->render('create', [
						'cartIdList' => $cartIdList, 'model' => $model, 'addressList' => $addressList
			]);
		}
		//处理从订单传来的数据
		if (isset($post['cartIdS'])) {
			$cartIdList = $post['cartIdS'];
			$view = Yii::$app->view;
			$cartList = $view->params['cartList'];
			$orderTotal = 0;
			$delCartStr = "";
			foreach ($cartIdList as $key => $cartId) {
				$orderTotal += $cartList[$cartId]['productTotal'];
				if ($key == 0) {
					$delCartStr .= "cartId = $cartId";
				} else {
					$delCartStr .= " or cartId = $cartId";
				}
			}
			$model->userId = Yii::$app->user->id;
			$model->status = ShopOrder::$WAIT_PAY;
			$model->expressId = $model->expressno = "12315";
			$model->amount = $orderTotal;
			$model->addressId = $post['address'];
			if ($model->save()) {
				
			} else {
				echo "<pre>";
				var_dump($model->attributes);
				var_dump($model->errors);
				echo "</pre>";
				exit;
			}
			//处理orderDetail
			foreach ($cartIdList as $key => $cartId) {
				$orderTotal += $cartList[$cartId]['productTotal'];
				$orderDetailModel = new OrderDetail();
				$orderDetailModel->orderId = $model->orderId;
				$orderDetailModel->productId = $cartList[$cartId]['productId'];
				$orderDetailModel->price = $cartList[$cartId]['price'];
				$orderDetailModel->productnum = $cartList[$cartId]['productnum'];
				if ($orderDetailModel->save()) {
					
				} else {
					echo "<pre>";
					var_dump($orderDetailModel->attributes);
					var_dump($orderDetailModel->errors);
					echo "</pre>";
					exit;
				}
			}
			foreach ($cartIdList as $key => $cartId) {
				
			}
			Cart::deleteAll($delCartStr);
			return $this->redirect(['view', 'id' => $model->orderId]);
		}
		$addressModel = new Address();
		//新建Address
		if ($addressModel->load(Yii::$app->request->post())) {
			$addressModel->userId = \Yii::$app->user->id;
			$addressModel->save();
			$cartIdList = $_SESSION['cartIdList'];
			$addressList = Address::findAll(["userId" => $userId]);
			$addressList = \yii\helpers\ArrayHelper::toArray($addressList);
			return $this->render('create', [
						'cartIdList' => $cartIdList, 'model' => $model, 'addressList' => $addressList
			]);
		}
	}

	/**
	 * Updates an existing ShopOrder model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param string $id
	 * @return mixed
	 */
	public function actionUpdate($id) {
		$model = $this->findModel($id);

		if ($model->load(Yii::$app->request->post()) && $model->save()) {
			return $this->redirect(['view', 'id' => $model->orderId]);
		} else {
			return $this->render('update', [
						'model' => $model,
			]);
		}
	}

	public function actionPay($id) {
		$model = $this->findModel($id);
		if ($model->userId != $this->userId) {
			return $this->error("你没有权限访问该页面");
		}
		$model->status = 1;
		$model->save();
		return $this->redirect(Url::toRoute(['shop-order/view', 'id' => $model->orderId]));
	}

	/**
	 * Deletes an existing ShopOrder model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param string $id
	 * @return mixed
	 */
	public function actionDelete($id) {
		$this->findModel($id)->delete();
		return $this->redirect(['index']);
	}

	/**
	 * Finds the ShopOrder model based on its primary key value.
	 * If the model is not found, a 404 HTTP exception will be thrown.
	 * @param string $id
	 * @return ShopOrder the loaded model
	 * @throws NotFoundHttpException if the model cannot be found
	 */
	protected function findModel($id) {
		if (($model = ShopOrder::findOne($id)) !== null) {
			return $model;
		} else {
			throw new NotFoundHttpException('The requested page does not exist.');
		}
	}

	public function beforeAction($action) {
		if (parent::beforeAction($action)) {
			if ($this->isGust()) {
				$this->redirect(Url::toRoute('site/login'));
			} else {
				$this->userId = Yii::$app->user->id;
			}
			return TRUE;
		} else {
			return FALSE;
		}
	}

}
